#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""

import os
import sys
import json
import requests
import pandas
import datetime
from lxml.etree import HTML


class Spider():
    def get_Cookie(self):
        return "JSESSIONID=BA4D0A868E24CFD9DDFB6779A86F8F8A-n1; acw_tc=7b39758515954723913517329ec99562d988ce73fedc8db57dbb30290fcf36"

    def get(self, max_page=1, Cookie=""):
        url = "https://manage.feezu.cn/manage/car/teleControl/init?start={}"

        if not Cookie:
            Cookie = self.get_Cookie()
        headers = {
            "Cookie": Cookie,
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
        }
        res = []
        for i in range(max_page + 1):
            url_ = url.format(i * 20)
            data = self.get_data(url_, headers=headers)
            res += self.parse_data(data)

        res = pandas.DataFrame(res, columns=["当前网点", "车牌号", "车型", "设备号", "状态", "更新时间"])
        now = datetime.datetime.now().date()
        try:
            os.mkdir("data")
        except:
            pass
        res.to_excel("./data/" + str(now) + ".xlsx", encoding="utf8")

    def get_data(self, url, **kwargs):
        return requests.get(url, **kwargs).text

    def parse_data(self, html):
        html = HTML(html)
        trs = html.xpath("//table/tbody/tr")
        res = []
        for tr in trs:
            t0 = tr.xpath("./td")[0].text
            t1 = tr.xpath("./td")[1].text
            t2 = tr.xpath("./td")[2].text
            t3 = tr.xpath("./td")[3].text
            t4 = tr.xpath("./td")[4].text
            t5 = tr.xpath("./td")[5].text
            if t0 != None:
                t0 = t0.strip()
            if t1 != None:
                t1 = t1.strip()
            if t2 != None:
                t2 = t2.strip()
            if t0 != None:
                t3 = t3.strip()
            if t4 != None:
                t4 = t4.strip()
            if t5 != None:
                t5 = t5.strip()
            res.append([t0, t1, t2, t3, t4, t5])

        return res


if __name__ == '__main__':
    Spider().get(max_page=142)
